package com.yx.fx.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.yx.fx.common.model.ExcelAlias;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * 通用excel表格工具类
 *
 * @author 杨智杰
 * @since 2021/9/7 10:06
 */
@Slf4j
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param param 数据集合
     */
    public static void downExcel(Collection param) {
        downExcel(param, null);
    }

    /**
     * 导出excel
     *
     * @param alias 别名
     * @param param 数据集合
     */
    public static void downExcel(Collection param, List<ExcelAlias> alias) {
        downExcel(param, alias, IdUtil.simpleUUID() + ".xlsx");
    }

    /**
     * 导出excel
     *
     * @param alias    别名
     * @param param    数据集合
     * @param fileName 文件名
     */
    public static void downExcel(Collection param, List<ExcelAlias> alias, String fileName) {
        downExcel(param, alias, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(), fileName);
    }

    /**
     * 导出excel
     *
     * @param alias    别名
     * @param param    导出列表
     * @param response response
     * @param fileName 文件名
     */
    public static void downExcel(Collection param, List<ExcelAlias> alias, HttpServletResponse response, String fileName) {
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        if (CollUtil.isNotEmpty(alias)) {
            for (ExcelAlias ea : alias) {
                writer.addHeaderAlias(ea.getOrigin(), ea.getAlias());
            }
        }
        writer.write(param, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            writer.close();
            IoUtil.close(out);
        }
    }
}
